<template>
	<block>
		<view class="bg-white " style="font-size:14px;padding: 0 16rpx;" v-for="(item,index) in msg.mediaList"
			:key="index">
			<view class="wrap line-black" v-if="item.miType==1"
				style="font-size:14px;line-height:22px;white-space:pre-line !important; padding:5px 0;">
				{{item.miTitle}}
			</view>
			<view class="padding-top-xs" v-else-if="item.miType==2">
				 <van-image fit="widthFix" lazy-load :src="item.miUrl" width="100%" @click="previewImage(item.miUrl)">
				 </van-image>
			</view>
			<!--语音-->
			<view class="cu-list menu-avatar padding-top-xs" v-else-if="item.miType==3"
				style="overflow-x: hidden; overflow-y: auto;">
				<!-- {{item.currentTime}}   {{item.currentSeconds}} -->
				<view class="cu-item" style="background: #f3f3f3; border-radius: 8rpx; margin: 8rpx 0; height: 100rpx;">
					<view class="cu-avatar" style="background-color: #f3f3f3;">
						<i class="fa" :class="[item.isPlay?'fa-pause-circle-o':'fa-play-circle']"
							@click="playAudio(item,index)"
							style="color: #00b1ff;font-size: 64rpx; margin-right: 12rpx;"></i>
					</view>
					<view class="content" style="left: 115rpx; width: calc(100% - 96rpx - 170rpx);">
						<slider @change="swiperChange" :value="item.value" block-size="20" activeColor="#00b1ff"
							:disabled="!item.isPlay" :class="[!item.isPlay?'disabled':'']" style="margin: 20rpx;">
						</slider>
					</view>
					<view class="action" style="width: auto;margin-right: 12rpx;">
						<view class="text-grey text-xs">{{!!item.currentTime?item.currentTime:'00:00'}} /
							{{!!item.sumTime?item.sumTime:!!item.miDuration?item.miDuration:"未知"}}
						</view>
						<view class="text-grey text-xs">{{item.miTitle}}</view>
					</view>
				</view>
			</view>
			<!--视频-->
			<view class="cu-list menu-avatar padding-top-xs" v-else-if="item.miType==4"
				style="overflow-x: hidden; overflow-y: auto;">
				<view class="cu-item" @click="showVideo(item,index)"
					style="background: #f3f3f3; border-radius: 8rpx; margin: 8rpx 0; height: 100rpx;">
					<view class="cu-avatar" style="background-color: #f3f3f3;">
						<image lazy-load :src="item.miUrl+'?x-oss-process=video/snapshot,t_100,f_png,m_fast,ar_auto'" width="100%" height="100%">
						</image>
						<!-- <i class="fa" :class="[fileIco(item.miTitle)]"
							style="color: #00b1ff;font-size: 64rpx; margin-right: 12rpx;"></i> -->
					</view>
					<view class="content" style="left: 115rpx;">
						<view class="text-black">
							<text class="text-cut"> {{item.miTitle}}</text>
						</view>
						<view class="text-gray text-sm flex">
							<text class="text-cut">(点击播放)</text>
						</view>
					</view>
					<view class="action" style="width: auto;margin-right: 12rpx;">
						<view class="text-grey text-xs">{{item.miDuration}}
						</view>
						<view class="text-grey text-xs">{{item.miSize}}</view>
					</view>
				</view>
				<view style="width:100%;" v-if="false">
					<view style="position:relative;" class="hxt-flex">
						<video v-if='fullScreen' :src="item.miUrl" @ended="closeVideo" @fullscreenchange="screenChange"
							:id="['video-'+index]" direction="0" autoplay="true" controls enable-play-gesture
							style="position:absolute; width:100%;height:100%;left:0; top:0; z-index:0;"></video>
						<view style="width: 100%;">
							<view style="padding-top:100%;position:relative;">
								<image :src="!!item.thumb?item.thumb:(item.miUrl+'?x-oss-process=video/snapshot,t_100,f_png,m_fast,ar_auto')" lazy-load="true"
									style="position:absolute; width:100%;height:100%;left:0; top:0; z-index: 1;">
								</image>
							</view>
						</view>
						<!-- <image mode="widthFix"
							:src="item.miUrl+'?x-oss-process=video/snapshot,t_100,f_png,m_fast,ar_auto'"
							:lazy-load="true" style="width:100%;height:100%;"></image> -->
						<view v-if="!!item.miUrl" @click="showVideo(item,index)"
							style=" position: absolute; width: 100%; height: 100%; top: 0; left: 0; background: rgba(0, 0, 0, .3); z-index: 1;">
							<view
								style="width: 64rpx; height: 64rpx; position: absolute; margin: auto;  top: 0;  left: 0;  right: 0; bottom: 0;">
								<i class="fa fa-play-circle" style="color: #F5F5F5;font-size: 64rpx;"></i>
							</view>
							<view
								style="width: 100%; height: 32rpx; position: absolute;color: #F5F5F5;font-size: 20rpx;bottom: 0; padding: 0 10rpx;">
								{{item.miDuration}}
								<view style="float: right;">{{item.miTitle}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="cu-list menu-avatar padding-top-xs" v-else-if="item.miType==7"
				style="overflow-x: hidden; overflow-y: auto;">
				<view class="cu-item" @click="previewFile(index)"
					style="background: #f3f3f3; border-radius: 8rpx; margin: 8rpx 0; height: 100rpx;">
					<view class="cu-avatar" style="background-color: #f3f3f3;">
						<i class="fa" :class="[fileIco(item.miTitle)]"
							style="color: #00b1ff;font-size: 64rpx; margin-right: 12rpx;"></i>
					</view>
					<view class="content" style="left: 115rpx;">
						<view class="text-black">
							<text class="text-cut"> {{item.miTitle}}</text>
						</view>
						<view class="text-gray text-sm flex">
							<text class="text-cut">(点击预览)</text>
						</view>
					</view>
					<view class="action">
						<view class="text-grey text-xs">{{item.miSize}}</view>
					</view>
				</view>
			</view>
		</view>

		<hxt-loading id="hxt-loading"></hxt-loading>
	</block>
</template>

<script>
	import * as hxt from "@/utils/hxt.js"
	export default {
		name: "notifyDetail",
		options: {
			styleIsolation: 'apply-shared'
		},
		props: {
			loadmsg: {
				type: Object,
				default: null
			},
		},
		data() {
			return {
				msg: this.loadmsg,
				fullScreen: false,
				
				innerAudioContext: null,
				miUrl: '',
				audiomx: -1,
			};
		},
		// watch: {
		// 	loadmsg: function(val) {
		// 		var _this = this;
		// 		this.msg = val;
		// 	}
		// },
		created() { //组件创建后，但还未挂载
			var _this = this;
			// this.msg.mediaList.forEach(function(item, index) {
			// 	if(item.miType!=3)return;
			// 	_this.$set(_this.msg.mediaList[index], 'isPlay', false);
			// 	_this.$set(_this.msg.mediaList[index], 'value', 0);
			// 	_this.$set(_this.msg.mediaList[index], 'currentSeconds', 0);
			// 	_this.$set(_this.msg.mediaList[index], 'currentTime', '00:00');
			// });
		},
		destroyed: function() {
			var _this = this,
				innerAudioContext = _this.innerAudioContext;
			if (!!innerAudioContext) {
				innerAudioContext.destroy();
			};
		},
		methods: {
			//图片预览
			previewImage: function(url) {
				var obj = this.msg.mediaList.filter(function(item) {
					return item.miType == 2;
				});
				var urls = obj.map(function(item) {
					return item.miUrl;
				});
				wx.previewImage({
					current: url, // 当前显示图片的http链接
					urls: urls // 需要预览的图片http链接列表
				});
			},
			pauseAudio: function(e) {
				var _this = this,
					innerAudio = _this.innerAudioContext;
				if (innerAudio && !innerAudio.paused) {
					innerAudio.pause();
				};
			},
			//音频播放器
			addAudio: function() {
				var _this = this,
					innerAudioContext = _this.innerAudioContext;
				if (!innerAudioContext) return;
				var getpaused = function() {
					setTimeout(() => { //解决onTimeUpdate第二次播放不会触发的坑
						var paused = innerAudioContext.paused;
					}, 100);
				};
				innerAudioContext.onCanplay(getpaused);
				innerAudioContext.onSeeking(getpaused);
				innerAudioContext.onPlay(() => {
					console.log('onPlay');
					hxt.loading(false);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'isPlay', true);
				});
				innerAudioContext.onPause(() => {
					_this.$set(_this.msg.mediaList[_this.audiomx], 'isPlay', false);
				});
				innerAudioContext.onEnded(function(res) {
					console.log('播放结束', res);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'isPlay', false);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'value', 0);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'currentSeconds', 0);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'currentTime', '00:00');
				});
			
				innerAudioContext.onTimeUpdate(() => {
					if (!innerAudioContext.duration || !innerAudioContext.currentTime) return;
					_this.$set(_this.msg.mediaList[_this.audiomx], 'sumTime', hxt
						.formatSeconds(
							innerAudioContext.duration));
					_this.$set(_this.msg.mediaList[_this.audiomx], 'value', parseInt(
						parseInt((
								innerAudioContext.currentTime / innerAudioContext.duration) *
							100)));
					_this.$set(_this.msg.mediaList[_this.audiomx], 'currentSeconds',
						innerAudioContext.currentTime);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'currentTime', hxt
						.formatSeconds(
							innerAudioContext.currentTime));
				});
			
				innerAudioContext.onError((res) => {
					hxt.loading(true);
					hxt.alert(res.errMsg, '播放失败');
					hxt.loading(false);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'isPlay', false);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'value', 0);
					_this.$set(_this.msg.mediaList[_this.audiomx], 'currentTime', '00:00');
					_this.$set(_this.msg.mediaList[_this.audiomx], 'currentSeconds', 0);
				});
			},
			playAudio: function(media, mx) {
				var _this = this,miUrl =  media.miUrl,
					innerAudioContext = _this.innerAudioContext;
				if (!innerAudioContext) {
					innerAudioContext = wx.createInnerAudioContext();
					_this.innerAudioContext= innerAudioContext;
					_this.addAudio();
				};
				console.log(media)
				if (!!media.isPlay) {
					innerAudioContext.pause();
				} else {
					if (miUrl != _this.miUrl) {
						if (!!_this.miUrl) {
							_this.$set(_this.msg.mediaList[_this.audiomx], 'isPlay', false);
							// _this.$set(_this.msg.mediaList[_this.audiomx], 'value', 0);
							// _this.$set(_this.msg.mediaList[_this.audiomx], 'currentTime', '00:00');
						};
						_this.miUrl = miUrl;
						_this.audiomx = mx;
						hxt.loading(true);
						innerAudioContext.src = encodeURI(miUrl); //天坑：IOS下url含有空格无法播放
						// innerAudioContext.currentTime = media.currentSeconds;
						innerAudioContext.startTime=(media.currentSeconds);
						innerAudioContext.autoplay = true;
					} else {
						innerAudioContext.play();
					}
				}
			},
			swiperChange: function(e) {
				var _this = this,
					innerAudioContext = _this.innerAudioContext;
				var value = e.detail.value;
				var sk = innerAudioContext.duration * (value / 100);
				innerAudioContext.seek(sk);
				_this.msg.mediaList[_this.audiomx].currentTime = hxt.formatSeconds(sk);
			},
			
			showVideo(item, index) { //弹出视频图层播放视频
				var _this = this,
					id = 'video-' + index;
				wx.getSystemInfo({
					success: function(res) {
						var isUpload = /(https):\/\/\S*/.test(item.miUrl);
						
							var obj = _this.msg.mediaList.filter(function(item) {
								return item.miType == 4;
							});
							var sources = obj.map(function(item) {
								return {
									url: item.miUrl,
									type: 'video',
									poster: item.miUrl +
										'?x-oss-process=video/snapshot,t_100,f_png,m_fast,ar_auto'
								};
							});
							var current = sources.findIndex(function(it) {
								return it.url == item.miUrl;
							});
							wx.previewMedia({
								sources: sources,
								current: current
							});
					}
				});
			},
			screenChange(e) {
				var _this = this,
					fullScreen = e.detail.fullScreen; //值true为进入全屏，false为退出全屏
				if (!fullScreen) { //退出全屏
					_this.videoContext.stop();
					_this.setData({
						fullScreen: false
					});
				} else { //进入全屏
					_this.videoContext.play();
					_this.setData({
						fullScreen: true
					});
				}
			},
			closeVideo(e) { //执行退出全屏方法			
				this.videoContext.exitFullScreen();
				this.setData({
					fullScreen: false
				})
			},
			fileIco: function(url) { //wxs方法
				var ico = 'fa-file-o';
				if (!!url) {
					var index = url.lastIndexOf('.');
					if (index > -1) {
						var str = url.substring(index + 1).toLowerCase();
						switch (str) {
							case 'doc':
							case 'docx':
								ico = 'fa-file-word-o';
								break;
							case 'xls':
							case 'xlsx':
								ico = 'fa-file-excel-o';
								break;
							case 'ppt':
							case 'pptx':
								ico = 'fa-file-powerpoint-o';
								break;
							case 'pdf':
								ico = 'fa-file-pdf-o';
								break;
						}
					}
				}
				return ico;
			},
			open: function(e) {
				var that = this,
					file = that.CurrentFile;
				hxt.loading(true);
				wx.openDocument({
					filePath: e,
					showMenu: true,
					// 文档打开格式记得写上，否则可能不能打开文档, 文档类型只能是一个
					// 若是想打开多种类型的文档，可以解析文档地址中的文档格式，动态复制到fileTpye参数
					// fileType: file.type,
					success: function(res) {
						//console.log('打开文档成功')
						hxt.loading(false);
					},
					fail: function(err) {
						hxt.loading(false);
						that.copyLk(file.miUrl, '文件地址复制成功,请粘贴到浏览器地址栏打开；预览失败原因:' + err.errMsg, "预览失败",e);
					}
				});
			},
			previewFile(index) { //文件预览
				var _this = this,CurrentFile = _this.msg.mediaList[index],isUpload = /(https):\/\/\S*/.test(CurrentFile.miUrl);
				if (!isUpload) {
					hxt.loading(true);
					wx.openDocument({
						filePath: CurrentFile.miUrl,
						showMenu: true,
						// 文档打开格式记得写上，否则可能不能打开文档, 文档类型只能是一个
						// 若是想打开多种类型的文档，可以解析文档地址中的文档格式，动态复制到fileTpye参数
						// fileType: file.type,
						success: function(res) {
							//console.log('打开文档成功')
							hxt.loading(false);
						},
						fail: function(err) {
							hxt.loading(false);
							_this.copyLk('', '文件预览失败,预览请【转发】文件到微信；预览失败原因:' + err.errMsg, "预览失败", CurrentFile.miUrl);
						}
					});
					return;
				};
				var filePath = wx.env.USER_DATA_PATH + "/" + hxt.ToMd5(CurrentFile.miUrl) + "/" + CurrentFile.miTitle;
				const fs = wx.getFileSystemManager();
				//判断文件/目录是否存在
				fs.access({
					path: filePath,
					success(res) {
						// 文件存在
						hxt.log('文件存在');
						_this.CurrentFile = CurrentFile;
						_this.open(filePath);
					},
					fail() {
						// 文件不存在或其他错误
						// (创建目录)
						fs.mkdir({
							dirPath: `${wx.env.USER_DATA_PATH}/${hxt.ToMd5(CurrentFile.miUrl)}`,
							recursive: false,
							success(res) {
								hxt.loading(true);
								wx.downloadFile({
									url: CurrentFile.miUrl,
									filePath: filePath,
									success: function(res) {
										hxt.log(res);
										hxt.loading(false);
										_this.CurrentFile = CurrentFile;
										_this.open(res.filePath);
									},
									fail: function(err) {
										hxt.log(err);
										hxt.loading(false);
										_this.copyLk(CurrentFile.miUrl,
											'文件地址复制成功,请粘贴到浏览器地址栏打开；下载失败原因：' + res.errMsg,
											"下载失败");
									}
								});
							},
							fail(err) {
								hxt.alert('创建目录失败，原因：' + err.errMsg);
								fs.rmdir({
									dirPath:`${wx.env.USER_DATA_PATH}/${hxt.ToMd5(CurrentFile.miUrl)}`,
									recursive:true
								});
							}
						});
					}
				});
			},
			copyLk: function(link, msg, title, path) {
				if (!link) {
					wx.showModal({
						title: title,
						content: msg,
						cancelText: '取消',
						confirmText: '转发',
						success: res => {
							if (res.confirm) {
								wx.shareFileMessage({
									filePath: path
								})
							};
						}
					});
					return;
				};
				wx.setClipboardData({
					data: link,
					success: function(res) {
						wx.getClipboardData({
							success: function(res) {
								if (!path) {
									return hxt.alert(msg, title);
								};
								wx.showModal({
									title: title,
									content: msg,
									cancelText: '确定',
									confirmText: '转发',
									success: res => {
										if (res.confirm) {
											wx.shareFileMessage({
												filePath: path
											})
										};
									}
								});
							}
						});
					}
				});
			},
		}
	}
</script>

<style>
	.disabled {
		opacity: 0.5;
	}
</style>
